 
layui.define('form', function(exports){
  var $ = layui.$
  ,layer = layui.layer
  ,laytpl = layui.laytpl
  ,setter = layui.setter
  ,view = layui.view
  ,admin = layui.admin
  ,common = layui.common
  ,form = layui.form;

  var $body = $('body');
  
  $(function(){
	  if (window.parent.window != window) {
	        window.top.location = setter.host+"/adminmanager/tologin";
	    }
  });
  //自定义验证
  form.verify({
    nickname: function(value, item){ //value：表单的值、item：表单的DOM对象
      if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
        return '用户名不能有特殊字符';
      }
      if(/(^\_)|(\__)|(\_+$)/.test(value)){
        return '用户名首尾不能出现下划线\'_\'';
      }
      if(/^\d+\d+\d$/.test(value)){
        return '用户名不能全为数字';
      }
    }
    
    //我们既支持上述函数式的方式，也支持下述数组的形式
    //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
    ,pass: [
      /^[\S]{6,12}$/
      ,'密码必须6到12位，且不能出现空格'
    ] 
  });
  
  
  //发送短信验证码
  admin.sendAuthCode({
    elem: '#LAY-user-getsmscode'
    ,elemPhone: '#LAY-user-login-cellphone'
    ,elemVercode: '#LAY-user-login-vercode'
    ,ajax: {
      url: layui.setter.base + 'json/user/sms.js' 
    }
  });
  
  //更换图形验证码
  $body.on('click', '#LAY-user-get-vercode', function(){
    var othis = $(this);
    this.src = '/drawImage?timestamp='+ new Date().getTime()
  });
  form.render();
  form.on('submit(LAY-user-login-submit)', function(obj){
      //请求登入接口
      admin.req({
        url: setter.host+'/adminmanager/login' 
        ,data: JSON.stringify(obj.field)
        ,type:'post'
        ,contentType: "application/json; charset=utf-8"
        ,dataType:'json'
        ,done: function(res){
          //请求成功后，写入 access_token
        	if(res.status == setter.response.statusCode.status_Success){
	          //登入成功的提示与跳转
        		offLogin(res.data);
          }else if(res.status == setter.response.statusCode.status_More_Role){
        	  common.changeRole(res.data.roles,undefined,offLogin,res.data.command);
          }else{
        	  layer.alert(res.msg);
          }
        }
      });
      return false;
    });
  function offLogin(data){
	  layui.sessionData('layuiSession',{
		  key:'command',
	      value: data
	  });
      layer.msg('登入成功', {
        offset: '15px'
        ,icon: 1
        ,time: 1000
      }, function(){
    	  location.href = setter.host+'/main'; 
      });
  }
  //对外暴露的接口
  exports('login', {});
});